package com.zhuiyun.educations.api.User.service.impl;

import com.zhuiyun.educations.util.HttpUtils;
import com.zhuiyun.educations.util.RedisUtil;
import org.apache.http.HttpResponse;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class CodeSender {

    private static final String HOST = "https://dfsns.market.alicloudapi.com";
    private static final String PATH = "/data/send_sms";
    private static final String METHOD = "POST";
    private static final String APP_CODE = "a9deaf83bcf54669b834484e59bd6f9f";

    public static boolean sendSms(String phoneNumber) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "APPCODE " + APP_CODE);
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
//        String time =  "";
        Map<String, String> bodys = new HashMap<>();
        String code = generateCode();
        RedisUtil.set(phoneNumber,code, 60);
        bodys.put("content", "code:" + code);
        bodys.put("phone_number", phoneNumber);
        bodys.put("template_id", "CST_ptdie100");

        try {
            HttpResponse response = HttpUtils.doPost(HOST, PATH, METHOD, headers, null, bodys);
            System.out.println(response.toString());
            return true; // 返回 true 表示短信发送成功
        } catch (Exception e) {
            e.printStackTrace();
            return false; // 返回 false 表示短信发送失败
        }
    }

    private static String generateCode() {
        Random random = new Random();
        int code = random.nextInt(9000) + 1000; // 生成1000到9999之间的四位随机数
        return String.valueOf(code);
    }

}
